package lv.dysnomia.portal.web

import scala.xml.Elem
import java.io.{ IOException, PrintWriter }
import scala.collection.immutable.Map

import javax.servlet.{ RequestDispatcher, ServletException }
import javax.servlet.http.{ HttpServlet, HttpServletRequest, HttpServletResponse }
import com.google.appengine.api.blobstore.{ BlobKey, BlobInfo, BlobInfoFactory, BlobstoreServiceFactory }

import java.util.{ List => JavaList }
import javax.jdo.{ PersistenceManager, Query }

import lv.dysnomia.server.entities.{ Song, SongDAO, MediaFile, MediaFileDAO }

import com.google.appengine.api.users.{ User, UserService, UserServiceFactory }

import java.net.URLEncoder

abstract class AbstractController extends HttpServlet {

  val defaultLocale: String = "lv"

  val locales: List[String] = List("en", "de", "lv", "ltg", "lt")

  def modelAndView(request: HttpServletRequest, response: HttpServletResponse): (Map[String, AnyRef], String)

  override def doGet(request: HttpServletRequest, response: HttpServletResponse): Unit = {
    val pathInfo = request.getPathInfo
    val (model, view) = modelAndView(request, response)
    for ((key, value) <- model) {
      request.setAttribute(key, value);
    }
    val storedLocale = request.getSession().getAttribute("locale")
    request.setAttribute("currentLocale",
      if (locales.contains(storedLocale)) storedLocale else defaultLocale)

    val url = request.getRequestURI
    val pickLanguage: String = localizationPanel(url).toString
    request.setAttribute("pickLanguage", pickLanguage)
    val rd = request.getRequestDispatcher("/WEB-INF/jsp"
      + request.getServletPath() + "/" + view + ".jsp")
    rd.forward(request, response)
  }

  override def doPost(request: HttpServletRequest, response: HttpServletResponse): Unit = {
    val pathInfo = request.getPathInfo
    val (model, view) = modelAndView(request, response)
    for ((key, value) <- model) {
      request.setAttribute(key, value);
    }
    val storedLocale = request.getSession().getAttribute("locale")
    request.setAttribute("currentLocale",
      if (locales.contains(storedLocale)) storedLocale else defaultLocale)
    val rd = request.getRequestDispatcher("/WEB-INF/jsp"
      + request.getServletPath() + "/" + view + ".jsp")
    rd.forward(request, response)
  }

  def localizationPanel(url: String): Elem = {
    val locs = Array("en", "de", "lv", "ltg", "lt")
    val urls = locales.map(s => "../servlet/locale?locale=" + s + "&url=" + URLEncoder.encode(url))
    return <td style="text-align:center"><small>
         <a href={urls(0)}>en</a>&nbsp;&nbsp;<a href={urls(1)}>de</a><br/><a href={urls(2)}>lv</a>&nbsp;&nbsp;<a href={urls(3)}>ltg</a>&nbsp;&nbsp;<a href={urls(4)}>lt</a>
     </small></td>
  }
}